import NProgress from 'nprogress'
import { notification } from 'ant-design-vue'
import router from '@/routes'
import { HOME_PATH, userIsGoToLogin, userIsGoToWhiteList } from '@/routes/routes'
import useStore from '@/stores'
import 'nprogress/nprogress.css'

NProgress.configure({ showSpinner: false }) // 切换路由时顶部是否出现转圈动画

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const { user, routes } = useStore()
  const hasToken = user.token
  // 已登录
  if (hasToken) {
    // 已登录的情况下访问登录页直接跳转首页
    if (userIsGoToLogin(to.path)) {
      next({ path: HOME_PATH })
      NProgress.done()
    }
    else {
      const hasGetUserInfo = user.userInfo
      // 有用户信息匹配到路由就跳转
      if (hasGetUserInfo) {
        if (to.matched.length === 0)
          from.name ? next({ name: from.name }) : next('/403')
        else
          next()
      }
      // 没有用户信息时获取信息后在跳转
      else {
        try {
          await user.getUserInfo()
          const roles = user.userInfo?.roles || []
          const accessedRoutes: any = await routes.generateRoutes(roles)
          console.log('🚀 ~ accessedRoutes:', accessedRoutes)
          accessedRoutes.forEach((route: any) => {
            router.addRoute(route)
          })
          next({ ...to, replace: true })
        }
        catch (error) {
          // 移除 token 并跳转登录页
          await user.resetToken()
          notification.error({
            message: 'error',
            description: 'The request for user information failed, please try again',
          })
          next(`/user/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  }
  // 未登录(白名单直接进 否则进登录页)
  else {
    console.log(to.path)
    if (userIsGoToWhiteList(to.path)) {
      next()
    }
    else {
      next(`/user/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
